# leetcode 144 二叉树的前序遍历

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        left = self.preorderTraversal(root.left)
        right = self.preorderTraversal(root.right)
        return [root.val] + left + right


# 非递归解法，用栈实现
class Solution:
    def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        stack = []
        result = []
        stack.append(root)
        while len(stack) > 0:
            node = stack.pop()
            if node is not None:
                result.append(node.val)

                # 要实现前序遍历，入栈顺序需要是先加入右节点，再加入左节点，出栈才能保证先左后右
                stack.append(node.right)
                stack.append(node.left)
        return result
